# -*- coding: utf-8 -*-
# -----------------------------------------
# @Time       : 2020/2/11 17:10
# @Author     : dqz 
# @Email      : 1406990390@qq.com
# @File       : ssh.py
# @Software   : PyCharm
# -----------------------------------------

import os
import paramiko
from paramiko.ssh_exception import AuthenticationException


def client(ip, cmd, pri_key, user='root', port=22, timeout=10):
    infos = {
        "status": True,
        "msg": "ok"
    }
    if not os.path.exists(pri_key):
        return None
    key = paramiko.RSAKey.from_private_key_file(pri_key)
    ssh = paramiko.SSHClient()
    # ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    info = None
    try:
        ssh.connect(hostname=ip, port=port, username=user, pkey=key)
        stdin, stdout, stderr = ssh.exec_command(cmd)
        #infos["stdin"] = stdin.read().decode("utf-8")
        infos["stdout"] = stdout.read().decode("utf-8")
        infos["stderr"] = stderr.read().decode("utf-8")
    except AuthenticationException as auth_failed:
        infos["status"]=False
        infos["msg"]=str(auth_failed)
    except Exception as e:
        infos["status"]=False
        infos["msg"]=str(e)
    finally:
        if ssh:
            ssh.close()
    return infos
